package vn.gq.udv.comic;


import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import vn.gq.udv.comic.fragment.ChapterListFragment;
import vn.gq.udv.comic.fragment.IntroFragment;
import vn.gq.udv.comic.model.item.Bookmark;
import vn.gq.udv.comic.model.item.ChapterItem;
import vn.gq.udv.tab.SwipeyTabs;
import vn.gq.udv.tab.SwipeyTabsAdapter;
import vn.gq.udv.utils.DialogUtils;
import vn.gq.udv.utils.IOUtils;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainActivity extends BaseActivity {

	private static final String [] TITLES = {
		"GIỚI THIỆU",
		"DANH MỤC",
	};

	private SwipeyTabs mTabs;
	private ViewPager mViewPager;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_swipeytab);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mViewPager.setPageMargin(10);
		mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);

		SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
				getSupportFragmentManager());
		mViewPager.setAdapter(adapter);
		mTabs.setAdapter(adapter);
		mViewPager.setOnPageChangeListener(mTabs);
		mViewPager.setOffscreenPageLimit(2);
		mViewPager.setCurrentItem(1);
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				showPopUpBookmark();
			}
		}, 2000);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
			case android.R.id.home:
				onBackPressed();
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private class SwipeyTabsPagerAdapter extends FragmentPagerAdapter implements
		SwipeyTabsAdapter {
	
		private final Context mContext;
		
		public SwipeyTabsPagerAdapter(Context context, FragmentManager fm) {
			super(fm);
		
			this.mContext = context;
		}
		
		@Override
		public Fragment getItem(int position) {
			switch(position) {
				case 0:
					return IntroFragment.newInstance();
				default:
					return ChapterListFragment.newInstance();
			}
		}
		
		@Override
		public int getCount() {
			return TITLES.length;
		}
		
		public TextView getTab(final int position, SwipeyTabs root) {
			TextView view = (TextView) LayoutInflater.from(mContext).inflate(
					R.layout.swipey_tab_indicator, root, false);
			view.setText(TITLES[position]);
			view.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					mViewPager.setCurrentItem(position);
				}
			});
			
			return view;
		}
	
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}
	
	public void showPopUpBookmark() {
		try {
			BookmarkHelper bookmarkHelper = BookmarkHelper.newInstance(MainActivity.this);
			
			if (bookmarkHelper.hasBookmark()) {
				
				final Bookmark bookmark = bookmarkHelper.loadBookmark();
				
				final ChapterItem chapterItem = new ChapterItem(bookmark.getChapterId(), bookmark.getTitle());
				
				String msg = String.format("Bạn có muốn đọc tiếp Trang %d \"%s\"", bookmark.getPosition()+1, bookmark.getTitle());
				
				DialogUtils.newInstance(MainActivity.this).showConfirm(msg, new DialogUtils.OnDialogConfirmListener() {
					
					@Override
					public void onOk() {
						startChapter(chapterItem, bookmark.getPosition());
					}
					
					@Override
					public void onCancel() {
						
					}
				});
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void startChapter(final ChapterItem chapterItem, final int position) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				String json;
				try {
					json = IOUtils.convertStreamToString(new GZIPInputStream(getAssets().open(String.format("data/%s", chapterItem.getChapterId()))));
					JSONArray imageArr = (JSONArray) new JSONTokener(json).nextValue();
					ArrayList<String> imagesData = new ArrayList<String>();
					for (int i=0;i<imageArr.length();i++) {
						imagesData.add(imageArr.getString(i));
					}
					ReaderActivity.startActivity(MainActivity.this, chapterItem, imagesData, position);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}).run();
	}

}
